<?php
/*************************************************************************
 * Generate and resize the images 
 *************************************************************************/

require_once dirname(dirname(__FILE__)).'/config/config.inc.php';

/**
 * Generate the customizable image from an image
 * @param string $srcPath Absolute path of source image
 * @param string $srcType Type of source image ( jpg|jpeg|png )
 * @param string $desPath Absolute path of destination image
 * @param string $desType Type of destination image ( jpg|jpeg|png )
 * @param int $desWidth Width of destination image
 * @param int $desHeight Height of destination image
 * @param int $quality (Default: 80) Quality of destination image ( 1..100 )
 */
function imageGenImage($srcPath, $srcType, $desPath = '', $desType, $desWidth, $desHeight, $quality = 80) {
  $srcInfos = getimagesize($srcPath);

  if ($srcType == 'jpg'
    || $srcType == 'jpeg'
    || $srcType == 'image/jpeg'
    || $srcType == 'image/pjpeg'
  ) $srcType = 'jpeg';
  
  if ($srcType == 'png' || $srcType == 'image/png') $srcType = 'png';

  if ($desType == 'jpg' || $srcType == 'jpeg') $desType = 'jpeg';
  
  //standardize the image
  $desWidth = ($srcInfos[0] > $desWidth) ? $desWidth : $srcInfos[0];
  $desHeightTmp = $desWidth*($srcInfos[1]/$srcInfos[0]);

  $desHeight = ($desHeightTmp > $desHeight) ? $desHeight : $desHeightTmp;
  $desWidth = $desHeight*($srcInfos[0]/$srcInfos[1]);

  #must user imagecreatetruecolor instead of imagecreate because imagecreate will return an very ugly image
  $desImg = imagecreatetruecolor($desWidth,$desHeight);
  $srcImg =  @call_user_func("imagecreatefrom$srcType", $srcPath);

  if ($srcImg != false) {
    imagecopyresampled($desImg, $srcImg, 0, 0, 0, 0, $desWidth, $desHeight, $srcInfos[0], $srcInfos[1]);
  
    #build the image if the dest path is specified
    if ($desPath != '') {
      call_user_func("image$desType", $desImg, $desPath, $quality);
      imagedestroy($desImg);
      return true;
    
    # if des path is not specified then return img data
    } else {
      ob_start();
      call_user_func("image$desType", $desImg, '', $quality);
      $imgData = ob_get_contents();
      ob_end_clean();
      imagedestroy($desImg);
      return $imgData;
    }
  }
  
  return false;
}